<template>
  <a-row>
    <div v-show="tableDataLists.length" class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <a-col :span="2" style="float: right;">
          <ExportFile
            :fetch="getDownloadData"
            :fields="jsonFields"
            name="downloadFile.xls"
          >
            <a-button
              class="editable-add-btn"
              type="primary"
              :loading="iconLoading"
              >导出</a-button
            >
          </ExportFile>
        </a-col>
      </a-row>
      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
          @change="handleTableChange"
        >
        <template slot="uploadTime" slot-scope="text">
          {{timeFormatter(text)}}
        </template>
        </a-table>
      </a-row>
    </div>
    <a-empty v-show="!tableDataLists.length">
      <span slot="description" style="color:grey;">
        请输入搜索数据
      </span>
    </a-empty>
  </a-row>
</template>

<script>
import api from "@/server/ncCheckConfig";
import { columns } from "./tableConfig";
import ExportFile from "vue-json-excel";
import moment from "moment";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
      jsonFields[item.title] = item.dataIndex;
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      tableColumns: columns,
      tableDataLists: [],
      isLoading: false,
      jsonFields: buildJsonFields([...columns, {
      title: "登录用户",
      dataIndex: "loginName",
      width: "100px",
      ellipsis: false,
      ellipsis: true
    }]),

      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击分页时事件
        onChange: (current, size) => {
          let _this = this;
          this.getAllRepair({ pageNum: current }, "tableDataLists");
        }
      },
      iconLoading: false
    };
  },
  computed: {},
  watch: {
    searchData: function(newVal, oldVal) {
      let _this = this;
      _this.getData({ pageNum: 1 });
    }
  },
  created() {},
  mounted() {
    // this.getData({ pageNum: 1 });
  },
  methods: {
    timeFormatter(time) {
      console.log("time",time);
      return moment((time-8*60*60)*1000).format(`YYYY-MM-DD HH:mm:ss`)
    },
    getData(parames) {
      this.getAllRepair(parames, "tableDataLists");
    },
    handleTableChange(pagination) {
      this.paginationOpt.current = pagination.current;
    },
    // Table 获取数据
    async getAllRepair(parames, key) {
      let _this = this;
      let { pageNum } = parames;
      _this.isLoading = true;
      let {modulType,servoProductTime, ...rest} = _this.searchData
      if(modulType == ""){
        modulType = 0
      }
      if(servoProductTime && servoProductTime != "") {
        servoProductTime = moment(servoProductTime).format("YYYY-MM")
      }else{
        servoProductTime=""
      }
      // let {beginTime,endTime,...rest} = _this.searchData
      const res = await api.selByModulType({
        username:  localStorage.getItem('username') ?  localStorage.getItem('username') : '',
        pageNum,
        pageSize: _this.paginationOpt.defaultPageSize,
        modulType,
        servoProductTime,
        ...rest
      });
      _this.isLoading = false;
      if (res.msgCode !== 0) {
        if(res.msgCode == -1) {
          this.$message.error("请选择产品类型")
        }
        this.paginationOpt.total = 0
        this[key] = []
        return;
      }
      this.paginationOpt.current = pageNum || 1
      this.paginationOpt.total = res.data.Total || 0;
      let newObj = res.data.Content || [];
      this[key] = newObj;
    },
    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      let {modulType,servoProductTime, ...rest} = _this.searchData
      if(modulType == ""){
        modulType = 0
      }
      if(servoProductTime && servoProductTime != "") {
        servoProductTime = moment(servoProductTime).format("YYYY-MM")
      }else{
        servoProductTime=""
      }
      const res = await api.selByModulType({
        username:  localStorage.getItem('username') ?  localStorage.getItem('username') : '',
        pageNum,
        pageSize,
        modulType,
        servoProductTime,
        ...rest
      });

      if (res.msgCode !== 0) {
        return;
      }
      let list = res.data.Content
      list.forEach(e=> {
        if(e.uploadTime && typeof e.uploadTime == "number") {
          e.uploadTime = moment((e.uploadTime-8*60*60)*1000).format(`YYYY-MM-DD HH:mm:ss`)
        }
      })
      return list;



    },
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}
.dialog-content {
  padding: 16px;
  height: 70vh;
  overflow: auto;
}
.dialog-footer {
  /* display: flex; */
  width: 100%;
  text-align: center;
}
.dialog-footer .footer-btn {
  margin-right: 16px;
}
</style>
